import pandas as pd
import numpy as np
import talib as ta
import datetime

from config import stime, stime1, etime, etime1


now_time = datetime.datetime.now()
stock_list = []


def get_minute_data(t, minute="09:35"):
    t = t[t.minute == minute]
    return t.iloc[-1, :]

def get_minute_data2(t, minute="09:35"):
    t = t[t.minute == minute]
    return t.iloc[-1, 0:1]

def get_daily_price(group):
    selector1 = ((group.index.hour == 14) & (group.index.minute == 50))
    selector2 = ((group.index.hour == 9) & (group.index.minute == 35))
    selector3 = ((group.index.hour == 9) & (group.index.minute == 40))
    selector4 = ((group.index.hour == 9) & (group.index.minute == 45))
    selector5 = ((group.index.hour == 9) & (group.index.minute == 50))
    selector6 = ((group.index.hour == 9) & (group.index.minute == 55))
    return pd.Series([None if group.loc[selector1].empty else group.loc[selector1].close[0],
                      None if group.loc[selector2].empty else group.loc[selector2].close[0],
                      None if group.loc[selector3].empty else group.loc[selector3].close[0],
                      None if group.loc[selector4].empty else group.loc[selector4].close[0],
                      None if group.loc[selector5].empty else group.loc[selector5].close[0],
                      None if group.loc[selector6].empty else group.loc[selector6].close[0]])

def get_daily_price_v2(group, mins=["14:50","09:35","09:40","09:45","09:40"]):
    return pd.Series([None if group.loc[group.minute == m].empty else group.loc[group.minute == m].close[0] for m in mins])

#// 大单次数
#// 超大单次数
def money_flow_transfer(flows, buy_column, sell_column):
    buy_20 = flows[buy_column].rolling(4).sum()
    buy_40 = flows[buy_column].rolling(8).sum()
    buy_80 = flows[buy_column].rolling(16).sum()
    buy_160 = flows[buy_column].rolling(32).sum()
    sell_20 = flows[sell_column].rolling(4).sum()
    sell_40 = flows[sell_column].rolling(8).sum()
    sell_80 = flows[sell_column].rolling(16).sum()
    sell_160 = flows[sell_column].rolling(32).sum()
    flows[buy_column + '_20'] = buy_20.apply(lambda x: np.round(np.log(x + 1), 3))
    flows[buy_column + '_40'] = buy_40.apply(lambda x: np.round(np.log(x + 1), 3))
    flows[buy_column + '_80'] = buy_80.apply(lambda x: np.round(np.log(x + 1), 3))
    flows[buy_column + '_160'] = buy_160.apply(lambda x: np.round(np.log(x + 1), 3))

    flows[buy_column + '_40_j3'] = np.round(ta.EMA(flows[buy_column + '_40'].values, timeperiod=3), 2)
    flows[buy_column + '_40_j5'] = np.round(ta.EMA(flows[buy_column + '_40'].values, timeperiod=5), 2)

    flows[sell_column + '_20'] = sell_20.apply(lambda x: np.round(np.log(x + 1), 3))
    flows[sell_column + '_40'] = sell_40.apply(lambda x: np.round(np.log(x + 1), 3))
    flows[sell_column + '_80'] = sell_80.apply(lambda x: np.round(np.log(x + 1), 3))
    flows[sell_column + '_160'] = sell_160.apply(lambda x: np.round(np.log(x + 1), 3))

    flows[sell_column + '_40_j3'] = np.round(ta.EMA(flows[sell_column + '_40'].values, timeperiod=3), 2)
    flows[sell_column + '_40_j5'] = np.round(ta.EMA(flows[sell_column + '_40'].values, timeperiod=5), 2)

    flows[buy_column + '_20_r'] = np.round(buy_20 / (sell_20 + buy_20 + 1), 2)
    flows[buy_column + '_40_r'] = np.round(buy_40 / (sell_40 + buy_40 + 1), 2)
    flows[buy_column + '_80_r'] = np.round(buy_80 / (sell_80 + buy_80 + 1), 2)
    flows[buy_column + '_160_r'] = np.round(buy_160 / (sell_160 + buy_160 + 1), 2)

    flows[buy_column + '_40r_j3'] = np.round(ta.EMA(flows[buy_column + '_40_r'].values, timeperiod=3), 2)
    flows[buy_column + '_40r_j5'] = np.round(ta.EMA(flows[buy_column + '_40_r'].values, timeperiod=5), 2)

def fib_yield_for(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
        yield a

def fib_(data, column, n = 9):
    for i in fib_yield_for(n):
        data[column + "_fib" + str(i)] = np.around(data[column] * 100 / data[column].shift(i) - 1, 3)

all_flows = None

for symbol in stock_list:

    ## 查询 日线
    histories_1d = get_price([symbol], stime, etime,
                             '1d', ['close', 'quote_rate', 'amp_rate', 'turnover_rate'], #  涨跌幅 振幅 换手
                             True,  # 是否跳过停牌
                             "pre",  # 前复权
                             0,  # 天数
                             is_panel=0)[symbol]
    ### 日线转换
    ### 求 fib close 比例, 用于判断长期短期趋势
    ### 求 与大盘相关系数  用于判断 强弱（日线，分时）
    ### 获取最近一段时间的换手率  fib 换手
    ### 63 日均线 极小值？？
    ### 求短期量价关系
    histories_1d['3d_up'] = histories_1d.close * 100 / histories_1d.close.shift(3) - 1
    histories_1d['turnover_rate_2'] = histories_1d.turnover_rate.shift(2)
    ## 查询分钟线
    histories_5m = get_price([symbol], stime + " 09:30", etime + " 15:00", "5m", ['close'], True, 'pre', 0, is_panel=0)[
        symbol]
    histories_5m["index"] = histories_5m.index
    histories_5m['day'] = pd.to_datetime(histories_5m.index.date, format='%Y-%m-%d')
    histories_5m["minute"] = histories_5m["index"].apply(lambda x: x.strftime("%H:%M"))


    #gg = histories_5m.groupby("day").apply(get_minute_data, minute="09:40")["close"]
    histories_1d_ret = histories_5m.groupby("day").apply(get_daily_price_v2)
    histories_1d_ret.columns = ['14:55', '09:35', '09:40', '09:45', '09:50', '09:55']
    ### 分钟线转日线
    flows = get_money_flow_step([symbol], stime1 + " 09:30", etime1 + " 14:50",
                                "5m",
                                ['act_buy_xl', 'act_buy_l', 'act_buy_m', 'act_sell_xl', 'act_sell_l', 'act_sell_m',
                                 'dde_l'],
                                None, is_panel=0)[symbol]
    #### 超大判断次数，大单判断数量
    flows['day'] = pd.to_datetime(flows.index.date, format='%Y-%m-%d')
    ##### 主买对价格的比例 主卖对价格的比例
    flows['up_20m'] = (histories_5m.close/histories_5m.close.shift(5)).apply(lambda x: np.round(x-1, 3) * 100)
    flows['up_40m'] = (histories_5m.close/histories_5m.close.shift(9)).apply(lambda x: np.round(x-1, 3) * 100)
    flows['up_80m'] = (histories_5m.close/histories_5m.close.shift(17)).apply(lambda x: np.round(x-1, 3) * 100)
    flows['up_160m'] = (histories_5m.close/histories_5m.close.shift(33)).apply(lambda x: np.round(x-1, 3) * 100)
    flows = flows.loc[((flows.index.hour == 14) & (flows.index.minute == 50))]
    flows.index = flows.day
    flows['symbol'] = symbol
    ## 查询flow 线
    #### flow 分钟线 转日线
    ## 合并 三个日线
    flows = flows.join(histories_1d)
    flows = flows.join(histories_1d_ret)
    flows['date'] = flows.index
    # flows.index == range(flows.s)
    if all_flows is not None:
        all_flows = pd.concat([all_flows, flows], ignore_index=True)
        # all_flows.append(flows)
    else:
        all_flows = flows
    ### 调 xgboost

